package com.liaobowen.util;

import com.liaobowen.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    //配置文件地址
    private static String filePath = "mybatis-config.xml";//因为配置文件放置在src路径目录下，所可以直接写文件名就行了，不然得写路径地址
    private static SqlSessionFactory sqlSessionFactory;
    private static SqlSession sqlSession;

    static {
        //获取配置文件的流信息
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //解析配置文件流信息，获取sqlSessionFactory实例对象
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    /**
     * @param mapperClass
     * @param <T>
     * @return 通过自己封装的该工具类，获取相应的mapper接口
     */
    public static <T> T getObjectMapper(Class<T> mapperClass) {
        //通过工厂类去打开SqlSesson会话
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //通过SqlSession 获得对应的接口
        return sqlSession.getMapper(mapperClass);
    }

    /**
     * 提交事务
     */
    public static void commit() {
        sqlSession.commit();
    }

}
